<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="患者姓名">
          <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="searchForm.departmentId" placeholder="请选择科室" clearable>
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="未到诊" value="no_show" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'appointment:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增预约
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        stripe
      >
        <el-table-column prop="appointmentId" label="预约编号" min-width="120" />
        <el-table-column label="患者信息" min-width="150">
          <template #default="scope">
            <div>{{ scope.row.patientName }}</div>
            <div class="text-secondary">{{ scope.row.patientPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column label="医生信息" min-width="150">
          <template #default="scope">
            <div>{{ scope.row.doctorName }}</div>
            <div class="text-secondary">{{ scope.row.departmentName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="预约时间" min-width="180">
          <template #default="scope">
            <div>{{ formatDate(scope.row.appointmentDate) }}</div>
            <div class="text-secondary">{{ scope.row.timeSlot }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="visitReason" label="就诊原因" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'appointment:read'"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'appointment:update'"
              :disabled="['completed', 'cancelled'].includes(scope.row.status)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="handleCancel(scope.row)"
              v-permission="'appointment:cancel'"
              v-if="['pending', 'confirmed'].includes(scope.row.status)"
            >
              取消
            </el-button>
            <el-button 
              type="success" 
              size="small"
              @click="handleCheckin(scope.row)"
              v-permission="'appointment:checkin'"
              v-if="scope.row.status === 'confirmed'"
            >
              到诊
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 取消预约对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消预约"
      width="500px"
    >
      <el-form :model="cancelForm" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            placeholder="请输入取消原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { appointmentAPI, departmentAPI } from '@/utils/api'
import { formatDateTime, formatDate } from '@/utils/date'
import { Plus } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)
const cancelLoading = ref(false)

// 科室列表
const departments = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  patientName: '',
  doctorName: '',
  departmentId: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref([])

// 监听日期范围变化
const updateDateRange = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    searchForm.startDate = dateRange.value[0]
    searchForm.endDate = dateRange.value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
})

// 取消预约对话框
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelForm = reactive({
  appointmentId: '',
  reason: ''
})
const currentAppointment = ref(null)

// 获取预约状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊',
    '预约中': '预约中',
    '已确认': '已确认',
    '已取消': '已取消',
    '已到诊': '已到诊',
    '未到诊': '未到诊'
  }
  return statusMap[status] || status
}

// 获取预约状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning',
    '预约中': 'info',
    '已确认': 'primary',
    '已取消': 'danger',
    '已到诊': 'success',
    '未到诊': 'warning'
  }
  return typeMap[status] || ''
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    console.log('科室列表响应:', res) // 添加日志
    
    departments.value = res.data.departments || []
  } catch (error) {
    console.error('获取科室列表失败', error)
    console.log('错误详情:', error.message, error.response || error)
  }
}

// 获取预约列表
const getAppointments = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await appointmentAPI.getAppointments(params)
    console.log('预约列表响应:', res) // 添加日志
    
    // 适配后端返回的数据格式
    tableData.value = res.data.appointments || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取预约列表失败', error)
    console.log('错误详情:', error.message, error.response || error)
    // 拦截器已经显示错误消息，这里不需要重复显示
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getAppointments()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getAppointments()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAppointments()
}

// 新增预约
const handleCreate = () => {
  router.push('/appointments/create')
}

// 查看预约详情
const handleView = (row) => {
  router.replace({
    path: `/appointments/detail/${row.id}`
  })
}

// 编辑预约
const handleEdit = (row) => {
  router.push(`/appointments/edit/${row.id}`)
}

// 取消预约
const handleCancel = (row) => {
  currentAppointment.value = row
  cancelForm.appointmentId = row.id
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

// 确认取消预约
const confirmCancel = async () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请输入取消原因')
    return
  }
  
  cancelLoading.value = true
  try {
    await appointmentAPI.cancelAppointment(cancelForm.appointmentId, { 
      reason: cancelForm.reason 
    })
    ElMessage.success('预约已取消')
    cancelDialogVisible.value = false
    getAppointments()
  } catch (error) {
    ElMessage.error(error.message || '取消预约失败')
  } finally {
    cancelLoading.value = false
  }
}

// 患者到诊
const handleCheckin = async (row) => {
  try {
    await ElMessageBox.confirm('确认患者已到诊?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await appointmentAPI.checkinAppointment(row.id, {})
    ElMessage.success('已确认患者到诊')
    getAppointments()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  getAppointments()
  getDepartments()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: right;
  padding-top: 20px;
}

.text-secondary {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 